<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Exceptions\ApiException;
use App\Format\PosterInstitutionFormat;
use App\Models\PosterInstitution;

class PosterInstitutionService
{
    public function create(PosterInstitutionFormat $posterInstitutionFormat)
    {
        PosterInstitution::query()->create($posterInstitutionFormat->toArrayNotNull());
        return true;
    }

    public function getList(int $page, int $pageSize, array $search)
    {
        $builder = PosterInstitution::query()->where('is_hide', 'N');
        if (isset($search['name'])) {
            $builder->where('name', 'like', '%' . $search['name'] . '%');
        }
        $count = $builder->count();

        $list = $builder->skip(($page - 1) * $pageSize)->take($pageSize)->get();

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function getAdminList(int $page, int $pageSize, array $search)
    {
        $builder = PosterInstitution::query()->orderByDesc('id');
        if (isset($search['name'])) {
            $builder->where('name', 'like', '%' . $search['name'] . '%');
        }
        $count = $builder->count();

        $list = $builder->skip(($page - 1) * $pageSize)->take($pageSize)->get();

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function update(PosterInstitutionFormat $posterInstitutionFormat)
    {
        if (empty($posterInstitutionFormat->getId())) {
            throw new ApiException('缺少参数', 1);
        }
        $poster = PosterInstitution::query()->find($posterInstitutionFormat->getId());
        $data = $posterInstitutionFormat->toArrayNotNull();
        unset($data['id']);
        $poster->update($data);
        return true;
    }

    public function delete(int $id)
    {
        PosterInstitution::query()->find($id)->delete();
        return true;
    }
}
